<template>
  <div class="login-container">
    <el-card class="login-card" header="用户登录">
      <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="rules"
          label-width="80px"
          class="login-form"
      >
        <!-- 用户名输入框 -->
        <el-form-item label="用户名" prop="username">
          <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              prefix-icon="User"
          ></el-input>
        </el-form-item>

        <!-- 密码输入框 -->
        <el-form-item label="密码" prop="password">
          <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              prefix-icon="Lock"
          ></el-input>
        </el-form-item>

        <!-- 登录按钮 -->
        <el-form-item>
          <el-button
              type="primary"
              class="login-btn"
              @click="handleLogin"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import request from '../components/utils/request';

// 登录表单数据
const loginForm = ref({
  username: '',  // 用户名
  password: ''   // 密码
});

// 表单验证规则
const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
});

// 登录表单引用
const loginFormRef = ref(null);

// 处理登录逻辑
const handleLogin = async () => {
  if (!loginFormRef.value) return;

  try {
    const valid = await loginFormRef.value.validate();
    if (!valid) return;

    console.log('发送登录请求:', loginForm.value);

    // 使用 URLSearchParams 传递参数
    const params = new URLSearchParams();
    params.append('username', loginForm.value.username);
    params.append('password', loginForm.value.password);

    // 修改：使用 /user/login 而不是 /login
    const response = await request.post('/user/login', params, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    });

    console.log('登录响应:', response);

    if (response.code === 200 && response.data) {
      ElMessage.success('登录成功');
      localStorage.setItem('userInfo', JSON.stringify(response.data));
      // 跳转到仪表板页面
      window.location.href = '/admin/dashboard';
    } else {
      ElMessage.error(response.msg || '登录失败');
    }
  } catch (error) {
    console.error('登录错误:', error);
    ElMessage.error('登录失败，请检查网络连接');
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;  /* 占满整个屏幕高度 */
  background-color: #f5f7fa;
}

.login-card {
  width: 400px;  /* 登录卡片宽度 */
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.login-form {
  margin-top: 20px;
}

.login-btn {
  width: 100%;  /* 按钮占满宽度 */
}
</style>